import { getToken, setToken, getUser, setUser, removeToken } from '@/utils/auth.js'

import { login, getUserInfo, logOut } from '@/api/login.js'

let user = {
    state: {
        token: getToken(),
        user: getUser()
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
                // 保存token到本地
            setToken(token)
        },
        SET_USER(state, user) {
            state.user = user
                // 保存用户信息到本地
            setUser(user)
        }
    },
    // 这里主要是异步方法
    actions: {

        Login({ commit }, form) {

            return new Promise((resolve, reject) => {
                //  调用后台接口 获取token
                login(form.username.trim(), form.password).then(res => {
                    const resData = res.data
                    commit('SET_TOKEN', resData.data.token)

                    resolve(resData)
                }).catch(error => {
                    reject(error)
                })
            })


        },
        // 获取用户信息
        GetUserInfo({ commit }, token) {
            return new Promise((resolve, reject) => {
                getUserInfo(token).then(res => {
                    const resData = res.data
                    commit('SET_USER', resData.data)

                    resolve(resData)
                }).catch(err => {

                })
            })
        },
        // token作为json对象请求参数
        Logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logOut(state.token).then(res => {
                    const resData = res.data
                    if (resData.flag) {
                        commit('SET_TOKEN', '')
                        commit('SET_USER', '')
                            // 移除本地的token和用户信息
                        removeToken()
                    } else { return false }

                    resolve(resData)
                }).catch(err => {
                    reject()
                })
            })
        }




    }
}

export default user